package com.ztom.top100;

/**
 * 爬楼梯
 * <p>
 * https://leetcode-cn.com/problems/climbing-stairs/
 *
 * @author ZhangTao
 */
public class Code29ClimbStairs {

    public int climbStairs3(int n) {
        if (n < 0) {
            return 0;
        }
        return process(0, n);
    }

    private int process(int i, int target) {
        if (i == target) {
            // 到达目标台阶
            return 1;
        }
        int ways = 0;
        if (i + 1 <= target) {
            ways += process(i + 1, target);
        }
        if (i + 2 <= target) {
            ways += process(i + 2, target);
        }
        return ways;
    }

    public int climbStairs2(int n) {
        if (n < 0) {
            return 0;
        }
        int[] dp = new int[n + 1];
        dp[n] = 1;
        for (int i = n - 1; i >= 0; i--) {
            dp[i] = dp[i + 1] + (i + 2 <= n ? dp[i + 2] : 0);
        }
        return dp[0];
    }

    /**
     * 滚动变量
     *
     * @param n
     * @return
     */
    public int climbStairs(int n) {
        if (n < 0) {
            return 0;
        }
        // 记录 i + 1 的值
        int next = 0;
        // 记录 i + 2 的值
        int nextNext = 0;
        // 当前位置的方法数
        int count = 1;
        for (int i = n - 1; i >= 0; i--) {
            nextNext = next;
            next = count;
            count = next + nextNext;
        }
        return count;
    }
}
